<template>
  <custom-page :disable="disable">
    <view>
      <view style="padding: 0 40rpx;background-color: #FFFFFF;">
        <u--form
            labelPosition="left"
            ref="form1"
			:model="list"
			:rules="rules"
        >
		<u-form-item
		    labelAlign="center"
		    label="上传人脸"
		    prop="userInfo.avatar"
		    borderBottom
		    ref="item1"
		    labelWidth="200"
		
		>
		  <!-- <u-upload
		      @afterRead="afterRead"
		      @delete="deletePic"
						:fileList="fileList1"
		      name="1"
		      multiple
		      :maxCount="1"
		      uploadText="请上传人脸图片"
		      width="200"
		      height="200"
		  ></u-upload> -->
		  <u--image width="150" height="150" @click='btnphoto'  :src="img" shape="circle" style="flex:1;"></u--image>
		  <u-button type="success" size="small" style="width: 120rpx;border: 0;" @click="btnphoto">拍照</u-button>
		</u-form-item>
          <u-form-item
              labelAlign="center"
              label="姓名"
              prop="userInfo.real_name"
              :borderBottom="false"
              borderBottom
              ref="item1"
              labelWidth="200"
              :labelStyle="{'font-size':'50rpx'}"
          >
            <u--input
                placeholder="请输入姓名"
                border="none"
                width="300"
				v-model="list.userInfo.real_name"
            ></u--input>
          </u-form-item>
		 <u-form-item
              labelAlign="center"
              label="性别"
              prop="userInfo.sex"
              borderBottom
              ref="item1"
              labelWidth="200"
			  @click="showSex = true"
          >
            <u--input
                placeholder="请选择性别"
                border="none"
				disabled
				disabledColor="#ffffff"
				v-model="list.userInfo.sex"
            ></u--input>
			<u-icon
				slot="right"
				name="arrow-right"
		></u-icon>
          </u-form-item>
		  <u-form-item
		        labelAlign="center"
		        label="出生日期"
		        prop="userInfo.birthday"
		        borderBottom
		        ref="item1"
		        labelWidth="200"
				@click="showBirthday = true"
		    >
		      <u--input
		          placeholder="请选择出生日期"
		          border="none"
		  		disabled
		  		disabledColor="#ffffff"
				:value="list.userInfo.birthday | formatDate"
		      ></u--input>
		  	<u-icon
		  		slot="right"
		  		name="arrow-right"
		  ></u-icon>
		    </u-form-item>
          <u-form-item
              labelAlign="center"
              label="身份证"
              prop="userInfo.id_card"
              borderBottom
              ref="item1"
              labelWidth="200"

          >
            <u--input
                placeholder="请输入身份证"
                border="none"
                width="300"
				v-model="list.userInfo.id_card"
            ></u--input>
          </u-form-item>
          <u-form-item
              labelAlign="center"
              label="单位"
              prop="userInfo.word_unit"
              borderBottom
              ref="item1"
              labelWidth="200"
			  v-if="show_Word_unit"
          >
            <u--input
                placeholder="请输入单位"
                border="none"
                width="300"
				v-model="list.userInfo.word_unit"
            ></u--input>
          </u-form-item>
          
          <u-form-item
              labelAlign="center"
              label="手机号码"
              prop="userInfo.tel"
              borderBottom
              ref="item1"
              labelWidth="200"

          >
            <u--input
                placeholder="请输入手机号码"
                border="none"
                width="300"
				v-model="list.userInfo.tel"
				type='number'
            >
              <template slot="suffix">
                <u-code
                    ref="uCode"
                    @change="codeChange"
                    seconds="60"
                    changeText="X秒重新获取"
                ></u-code>
                <u-button
                    @tap="getCode"
                    :text="tips"
                    type="success"
                    class="bdr"
                ></u-button>
              </template>
            </u--input>
          </u-form-item>
          <u-form-item
              labelAlign="center"
              label="验证码"
              prop="userInfo.code"
              borderBottom
              ref="item1"
              labelWidth="200"
          >
            <u--input
                placeholder="请输入验证码"
                border="none"
                width="300"
				v-model="list.userInfo.code"
            ></u--input>
          </u-form-item>
        </u--form>
		<u-action-sheet
			:show="showSex"
			:actions="actions"
			title="请选择性别"
			@close="showSex = false"
			@select="sexSelect"
	>
				</u-action-sheet>
				<u-datetime-picker
				                :show="showBirthday"
				                v-model="list.userInfo.birthday"
				                mode="date"
								@cancel="showBirthday = false" @confirm = "chooseDate"
								:minDate="0"
				        ></u-datetime-picker>
      </view>
	  <!-- <view>{{img}}</view> -->
      <view style="padding: 0 40rpx;margin-top: 40rpx;">
        <u-button class="bdr" type="primary" size="large" @click="login">注册</u-button>
      </view>
      <!-- <custom-tabbar></custom-tabbar> -->
    </view>
  </custom-page>

</template>

<script>
	import Api from '@/util/api.js'
	export default {
		data(){
			return {
				disable:true,
				showSex:false,
				showBirthday:false,
				show_Word_unit:true,
				tips: '',
				value: '',
				fileList1:[],
				img:'',
				userInfo:'',
				list:{
					userInfo:{
						avatar:'',
						real_name:'',
						id_card:'',
						word_unit:'',
						tel:'',
						code:'',
						sex:'',
						birthday:''
					}
				},
				rules: {
				'userInfo.real_name': {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				},
				'userInfo.avatar': {
					type: 'string',
					// max: 1,
					required: true,
					message: '请上传人脸',
					trigger: [ 'change']
				},
				'userInfo.id_card': {
					type: 'string',
					max: 18,
					min:18,
					required: true,
					message: '请输入正确的身份证',
					trigger: [ 'change']
				},
				'userInfo.word_unit': {
					type: 'string',
					required: true,
					message: '请填写工作单位',
					trigger: ['blur', 'change']
				},
				'userInfo.tel': {
					type: 'number',
					required: true,
					message: '请输入正确的手机号码',
					trigger: [ 'change']
				},
				'userInfo.code': {
					type: 'number',
					max: 4,
					min:4,
					required: true,
					message: '请输入验证码',
					trigger: ['blur', 'change']
				},
				'userInfo.sex': {
					type: 'string',
					max: 1,
					required: true,
					message: '请选择性别',
					trigger: ['blur', 'change']
				},
				'userInfo.birthday': {
					type: 'number',
					// max: 1,
					required: true,
					message: '请选择出生日期',
					trigger: ['blur', 'change']
				},
			},
			actions: [
					{
						id:1,
						name: '男',
					},
					{
						id:2,
						name: '女',
					},
						],
						
			}
			
		},
		onLoad(e) {
			var that = this
			console.log(e)
			if('path' in e){
				that.show_Word_unit = false
				that.disable = false
				console.log('我进来了',that.disable)
			}
			if(localStorage.getItem('apply_userInfo')){
				that.list = JSON.parse(localStorage.getItem('apply_userInfo'))
				localStorage.removeItem("apply_userInfo");
			}
			if('link' in e){
				that.img = e.link
				that.list.userInfo.avatar = e.link
			}
			// var link = that.getQueryString('link')
			// that.img = link
			// if(link){
			// 	that.list.userInfo.avatar = link
			// 	that.img = link
			// }
			that.checkUser()
			console.log(that.userInfo)
		},
		methods:{
			// 选择日期
			chooseDate(e){
				console.log('日期',e)
				var that = this
				that.list.userInfo.birthday = e.value
				that.showBirthday = false
			},
			// 选择性别
			sexSelect(e) {
						this.list.userInfo.sex = e.name
						this.$refs.form1.validateField('userInfo.sex')
				},
			// 检查用户信息
			checkUser(){
				var that  = this
				var userInfo = that.userInfo;
					if(localStorage.getItem('userInfo')){
						that.userInfo = JSON.parse(localStorage.getItem('userInfo'))
					}else{
						uni.showToast({
						    icon: 'none',   
						    duration: 3000,
						    title: "当前用户未登录"
						});
						return;
					}
			},
			btnphoto() {
				var that=this;
				// var list = JSON.stringify(that.list)
				// localStorage.setItem('apply_userInfo',list)
				// uni.navigateTo({
				// 	// url: './messageList'
				// 	url:'../face/face'
				// })
				// return;
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album'], //从相册选择
						success: function (res) {
							console.log('临时图片路径',res)
						var formData = {
									category:'un',
									admin_id:that.userInfo.id
								}
							uni.showLoading({
								title: '上传中'
							});
							Api.getUpload(res.tempFilePaths[0],'fee_date',formData).then(res=>{
								console.log('res',res)
								that.img = res.data.detail.link
								that.list.userInfo.avatar = res.data.detail.link
								uni.hideLoading();
							})
										  
						}
					});
				// uni.navigateTo({
				// 	url:'../face/face'
				// })
			},
			//手机登录
			codeChange(text) {
			  this.tips = text;
			},
			getCode() {
				var that = this
				if(!that.list.userInfo.tel){
					uni.$u.toast('请输入手机号码')
					return;
				}
				
			  if (this.$refs.uCode.canGetCode) {
			    // 模拟向后端请求验证码
			    uni.showLoading({
			      title: '正在获取验证码'
			    })
				var data = {
					mobile:that.list.userInfo.tel
				}
				Api.sendSms(data).then(res=>{
					console.log('验证码',res)
					uni.hideLoading();
					if(res.msg == '发送成功'){
						uni.$u.toast('验证码已发送');
						this.$refs.uCode.start();
					}else{
						uni.$u.toast(res.msg);
					}
				})
				
			    // setTimeout(() => {
			    //   uni.hideLoading();
			    //   // 这里此提示会被this.start()方法中的提示覆盖
			    //   uni.$u.toast('验证码已发送');
			    //   // 通知验证码组件内部开始倒计时
			    //   this.$refs.uCode.start();
			    // }, 2000);
			  } else {
			    uni.$u.toast('倒计时结束后再发送');
			  }
			},
			change(e) {
			  console.log('change', e);
			},
			
			// 注册
			login(){
				var that = this
				// console.log(that.userInfo)
				this.$refs.form1.validate().then(res => {
					let userInfo = that.list.userInfo
					userInfo['user_id'] = that.userInfo.id
					// console.log('信息',res)
					// uni.$u.toast('校验通过')
					Api.updateUser(userInfo).then(res=>{
						console.log('注册',res)
						if(res.msg == '成功'){
							localStorage.setItem('userInfo',JSON.stringify(res.data))
							localStorage.removeItem("apply_userInfo")
							if(localStorage.getItem('type') == 6){
								uni.reLaunch({
									url: '/pages/Mstaff/Mstaff'
								});
							}else{
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}
							
						}else{
							uni.$u.toast(res.msg)
						}
					})
				}).catch(errors => {
					// uni.$u.toast('校验失败')
				})
			},
			// 截取url中的code方法
				// getQueryString(name) {
			 //        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			 //        var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
			 //        var context = "";
			 //        if (r != null) context = r[2];
			 //        reg = null;
			 //        r = null;
			 //        return context == null || context == "" || context == "undefined"
			 //          ? ""
			 //          : context;
			 //      },
			// 新增图片
				/*
			async afterRead(event) {
				var that = this
				console.log('上传图片',event)
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				console.log(that.fileList1)
				// for (let i = 0; i < lists.length; i++) {
				// 	const result = await this.uploadFilePromise(lists[i].url)
				// 	let item = this[`fileList${event.name}`][fileListLen]
				// 	this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
				// 		status: 'success',
				// 		message: '',
				// 		url: result
				// 	}))
				// 	fileListLen++
				// }
			},
			*/
		},
		filters: {
			formatDate(value) {
				console.log(value)
				if(value==''){
					return '';
				}
				let date = new Date(value);
				//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM; //月补0
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d; //天补0
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h; //小时补0
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m; //分钟补0
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s; //秒补0
				return y + '-' + MM + '-' + d; //年月日
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m+ ':' + s; //年月日时分秒
			}
		},
	}
</script>

<style lang="scss">
	.bdr {
		border: 0;
	}
</style>
